package database;

import entity.Province;
import manager.ProvinceManager;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Noi
 */
public class ProvinceManagerDB {

    private CallableStatement cstmt;
    private java.sql.Connection conn;
    private ResultSet rs;

    public ProvinceManagerDB(java.sql.Connection conn) {
        this.conn = conn;
    }

    public void loadData(ProvinceManager provinceManager) {
        try {
            cstmt = conn.prepareCall("{call sp_GetProvince}");
            rs = cstmt.executeQuery();
            while (rs.next()) {
                String provinceID = rs.getString("ProvinceID");
                String provinceName = rs.getString("ProvinceName");
                boolean status = rs.getBoolean("Status");
                Province obj = new Province(provinceID, provinceName, status);
                provinceManager.add(obj);
            }
            rs.close();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ProvinceManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void deleteProvince(Province obj) {
        try {
            cstmt = conn.prepareCall("{call sp_DeleteProvince(?)}");
            cstmt.setString(1, obj.getProvinceID());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ProvinceManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void insertProvince(Province obj) {
        try {
            cstmt = conn.prepareCall("{call sp_InsertProvince(?,?)}");
            cstmt.setString(1, obj.getProvinceID());
            cstmt.setString(2, obj.getProvinceName());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ProvinceManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateProvince(Province obj) {
        try {
            cstmt = conn.prepareCall("{call sp_UpdateProvince(?,?,?)}");
            cstmt.setString(1, obj.getProvinceID());
            cstmt.setString(2, obj.getProvinceName());
            cstmt.setBoolean(3, obj.isStatus());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ProvinceManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
